import { create } from 'zustand';
import { devtools, persist, createJSONStorage } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import { authApi } from '@/api/auth';
import { useUserStore } from '@/store/user';

interface AuthState {
  token: string | null;
  isAuthenticated: boolean;
  isLoading: boolean;

  // Actions
  login: (username: string, password: string) => Promise<void>;
  logout: () => void;
  setLoading: (loading: boolean) => void;
  setToken: (token: string) => void;
  clearAuth: () => void;
  refreshToken: () => Promise<void>;
}

export const useAuthStore = create<AuthState>()(
  devtools(
    persist(
      immer((set, get) => ({
        token: null,
        isAuthenticated: false,
        isLoading: false,

        login: async (username: string, password: string) => {
          try {
            set({ isLoading: true });

            const tokenData = await authApi.login({ username, password });

            if (!tokenData) {
              throw new Error('登录API返回数据为空');
            }

            // 尝试多种可能的数据结构
            const accessToken = tokenData.accessToken || tokenData.token || tokenData.data?.accessToken;
            const refreshToken = tokenData.refreshToken || tokenData.data?.refreshToken;

            if (!accessToken) {
              throw new Error('登录API返回数据格式错误，缺少accessToken');
            }

            // 获取用户信息
            try {
              await useUserStore.getState().getUserInfo();
            } catch {
              // 如果获取用户信息失败，使用一个默认用户对象
              const defaultUser = {
                username,
                name: username,
              };
              useUserStore.getState().setUser(defaultUser);
            }

            set({
              token: accessToken,
              isAuthenticated: true,
              isLoading: false,
            });
          } catch (error) {
            set({ isLoading: false });
            throw error;
          }
        },

        logout: () => {
          get().clearAuth();
          try {
            authApi.logout();
          } catch {
            // Logout error handling
          }
        },

        setLoading: (loading: boolean) => {
          set({ isLoading: loading });
        },

        setToken: (token: string) => {
          set({ token, isAuthenticated: true });
        },

        clearAuth: () => {
          set({
            token: null,
            isAuthenticated: false,
            isLoading: false,
          });
          // 同时清除用户信息和权限信息
          useUserStore.getState().clearUser();
          useUserStore.getState().clearPermissions();
        },

        refreshToken: async () => {
          try {
            const response = await authApi.refreshToken();
            set({
              token: response.accessToken,
            });
          } catch (error) {
            get().clearAuth();
            throw error;
          }
        },
      })),
      {
        name: 'auth-storage',
        storage: createJSONStorage(() => localStorage),
        partialize: (state) => ({
          token: state.token,
          isAuthenticated: state.isAuthenticated,
        }),
        version: 1,
        onRehydrateStorage: () => (state) => {
          console.log('Auth state rehydrated:', state);
        },
      }
    ),
    {
      name: 'auth-store',
    }
  )
);